//
//  ZMParser+Json.m
//  EIP
//
//  Created by mac on 15/3/19.
//  Copyright (c) 2015年 Leo. All rights reserved.
//

#import "NSObject+Json.h"

#import <objc/runtime.h>

#define Prefix @"kk_"

@implementation NSObject(ParserJson)

- (void)kk_parserJsonDictionary:(NSDictionary*)jsonDictionary {
    
    if (![jsonDictionary isKindOfClass: [NSDictionary class]]) {
        return;
    }
    
    NSObject *targetObject = self;
    
    while (targetObject.class != [NSObject class]) {
        
        unsigned int count = 0;
        //成员变量
        Ivar *ivars = class_copyIvarList(targetObject.class, &count);
        
        for (int i = 0; i < count; i++) {
            
            Ivar ivar = ivars[i];
            
            //  变量名称
            NSString *ivarName = [[NSString alloc] initWithUTF8String: ivar_getName(ivar)];
            
            //  变量类型
            //            NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
            //            NSLog(@"ivar = %@|%@", ivarType, ivarName);
            
            NSString* key = ivarName;
            ivarName = [ivarName substringFromIndex: 1];
            
            key = [key substringFromIndex: 1];
            
            if ([key hasPrefix: Prefix] && Prefix.length) {
                key = [key substringFromIndex: Prefix.length];
            }
            
            //  获取值
            id value = jsonDictionary[key];
            if (value != nil && ![value isKindOfClass: [NSNull class]]) {
                [self setValue: value forKey: ivarName];
            }
        }
        free(ivars);
        
        targetObject = [targetObject.superclass new];
    }
}



#pragma mark - 正则表达式
+ (BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

+ (BOOL)isValidateMobile:(NSString*)mobile {
    NSString * MobileRegex = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MobileRegex];
    return [regextestmobile evaluateWithObject: mobile];
}
@end
